﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BigLotterySyndicate.Classes;
using SyndicateDAO.DatabaseObject;
using SyndicateBusiness.Classes;

namespace BigLotterySyndicate.Secured.Users.Controls
{
    public partial class FormCreate : BaseUserControl
    {
        #region properties

        protected string UserNameValue
        {
            get { return this.txtName.Text; }
           
        }

        protected string EmailValue
        {
            get { return this.txtEmail.Text; }

        }

        protected bool IsAdminValue
        {
            get { return this.chbAdmin.Checked; }

        }


        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void ButtonContinue_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid)
                return;

            int uId=0;

            if (SaveForm(out uId))
            {
                InsertEventLogEntry("User [" + uId.ToString() + "] account created.");
                this.BasePage.Redirect(String.Format("/Secured/Users/Default.aspx?uId={0}", uId));
            }
            else
            { 
            
            }


        }

        private bool SaveForm(out int uId )
        {
            user u = new user();

            u.username = this.UserNameValue;
            u.email = this.EmailValue;
            u.isAdmin = this.IsAdminValue;

            string password = GenerateNewPassword();

            u.password = Utilities.EncodePassword(password);
            u.syndicateId = 1;
            u.funds = 0;
            u.isActive = false;
            u.isEnabled = true;

            bool result = this.BasePage.BusinessFacade.UserBL.InsertUser(u);

            uId = u.id;

            if (result)
                SendActivationEmail(u, password);

            return result;
        }

        private void SendActivationEmail(user u, string password)
        {
            fundsLog log = new fundsLog();

            log.amount = -1;
            log.description = "New Account token created: " + password;
            log.fromUserId = this.BasePage.LoggedInUser.id;
            log.toUserId = u.id;
            log.syndicateId = this.BasePage.LoggedInUser.syndicateId;
            log.moneyIn = true;
            log.dateCreated = DateTime.Now;

            this.BasePage.BusinessFacade.FundsLogBL.InsertEntry(log);


            //throw new NotImplementedException();
        }

        public static string GenerateNewPassword()
        {
            System.Guid guid = System.Guid.NewGuid();

            String[] strGuid = guid.ToString().Split('-');

            return "S" + strGuid[0];


            //return MCExtranet2010.Classes.Utilities.GeneratePassword();
        }
    }
}